package pl.edu.pw.mini.java2.Communicator.Server;

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 * Klasa odpowiadająca za tworzenie i obsługę GUI do zapisywania logów. 
 * @author Dymitr Załuin, Kamil Łysik
 */
public class ServerLogger {
	private static ServerLogger instance;
	private static boolean shallShowOnGUI = true;
	private JTextArea log;
	private JScrollPane areaScrollPane;

	private ServerLogger() {
		JFrame frame = new JFrame();
		frame.setTitle("Server logger");
		log = new JTextArea();
		areaScrollPane = new JScrollPane(log);
		areaScrollPane
				.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
		log.setEditable(false);
		frame.setLayout(new BorderLayout());
		frame.add(areaScrollPane, BorderLayout.CENTER);
		frame.setSize(500, 500);
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	}

	private void appendText(String s) {
		if (log == null)
			return;
		log.append(s + "\n");
		areaScrollPane.getVerticalScrollBar().setValue(
				areaScrollPane.getVerticalScrollBar().getMaximum());
	}

	/**
	 * Umieszcza tekst w logu.
	 * @param s Text.
	 */
	public synchronized static void print(String s) {
		if (shallShowOnGUI) {
			if (instance == null)
				instance = new ServerLogger();
			instance.appendText(s);
		} else
			System.out.println(s);
	}

}
